package com.github.chirspan.xaas.security.service;

import cn.hutool.core.util.StrUtil;
import com.github.chirspan.xaas.rbac.model.RbacUser;
import com.github.chirspan.xaas.rbac.service.IRoleService;
import com.github.chirspan.xaas.rbac.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException;
import org.springframework.stereotype.Service;

/**
 * *******description*******
 * <p>
 * *************************
 *
 * @author ChenPan
 * @date 2019/3/29 09:28
 */
@Slf4j
@Service
public class UserAuthService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    public AuthUserDetail loadUserByUsername(String username) throws Exception {

        if (StrUtil.isNotBlank(username)) {
            RbacUser user = userService.findUser(username);

            if (user == null) {
                throw new UsernameNotFoundException("用户不存在:" + username);
            }

            return new AuthUserDetail(user, roleService.findUserRole(user.getId()));
        } else {
            throw new UnauthorizedUserException("用户名不能为空！");
        }
    }
}
